package com.earthea.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.util.ReUtil;
import com.earthea.common.exception.EartheaException;
import com.google.common.base.Function;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 字符串工具
 */
public class StringUtil {

    private static final Pattern PATTERN = PatternPool.get("\\$\\{(.+?)\\}");

    public static String format(String input) {
        return format(input, PATTERN, System::getProperty);
    }

    public static String format(String input, String regex) {
        return format(input, PatternPool.get(regex), System::getProperty);
    }

    public static String format(String input, Function<String, String> function) {
        return format(input, PATTERN, function);
    }

    public static String format(String input, Pattern regex, Function<String, String> function) {
        if (StringUtils.isBlank(input)) {
            return input;
        }
        return ReUtil.replaceAll(input, regex, matcher -> {
            StringBuilder builder = new StringBuilder();
            int i = 0;
            while (matcher.find()) {
                String replace = function.apply(matcher.group(1));
                builder.append(input, i, matcher.start());
                builder.append(replace == null ? matcher.group(0) : replace);
                i = matcher.end();
            }
            builder.append(input.substring(i));
            return builder.toString();
        });
    }

}
